﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.IO;  
using System.Net;
using System.Xml.Linq;

namespace CloudAppRestDemoWeb.Pages {

  public class appWebLists : IHttpHandler {

public void ProcessRequest(HttpContext context) {

  string appWebUrl = context.Cache["SPAppWebUrl"].ToString();

  Uri uri = new Uri(appWebUrl + "/_api/web/lists/?$select=Title");
  HttpWebRequest requestGet = (HttpWebRequest)WebRequest.Create(uri);
  requestGet.Credentials = CredentialCache.DefaultCredentials;
  requestGet.Method = "GET";
  HttpWebResponse responseGet = (HttpWebResponse)requestGet.GetResponse();
      
  XDocument doc = XDocument.Load(responseGet.GetResponseStream());
  XNamespace ns_dataservices = "http://schemas.microsoft.com/ado/2007/08/dataservices";

  context.Response.ContentType = "text/html";
  StreamWriter innerWriter = new StreamWriter(context.Response.OutputStream);
  HtmlTextWriter writer = new HtmlTextWriter(innerWriter);

  // create an HTML ol element with list of lists in app web
  writer.RenderBeginTag(HtmlTextWriterTag.Ol);
  foreach (var list in doc.Descendants(ns_dataservices + "Title")) {
    writer.RenderBeginTag(HtmlTextWriterTag.Li);
    writer.Write(list.Value);
    writer.RenderEndTag(); // </li>
  }
  writer.RenderEndTag(); // </ol>

  writer.Flush();
  writer.Dispose();

}

    public bool IsReusable { get { return false;} }
  }
}